package com.tbit.uqbike.client.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.rabbitmq.client.Channel;
import com.tbit.common.constant.*;
import com.tbit.common.entity.BalanceChange;
import com.tbit.common.entity.TransationLog;
import com.tbit.common.entity.UserAccountMoney;
import com.tbit.uqbike.client.config.RefundSwitchConfig;
import com.tbit.uqbike.client.constant.*;
import com.tbit.uqbike.client.dao.capital.AdaPayLogDao;
import com.tbit.uqbike.client.dao.capital.RideFeeLogDao;
import com.tbit.uqbike.client.dao.capital.TransationLogDao;
import com.tbit.uqbike.client.dao.core.*;
import com.tbit.uqbike.client.dao.log.*;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.*;
import com.tbit.uqbike.client.pojo.newEntity.*;
import com.tbit.uqbike.client.pojo.vo.DepositData;
import com.tbit.uqbike.client.remote.sms.ClzySmsAuthUtil;
import com.tbit.uqbike.client.remote.sms.apistore.ApiStoreMsgUtils;
import com.tbit.uqbike.client.service.*;
import com.tbit.uqbike.client.util.DoubleUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * @Author: chen
 * @Description:
 * @Date: 创建于 15:58 2022/8/18
 */
//@Service("payQueueListenter")
@Component
public class PayQueueListenter {

    private final static Logger log = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);

    @Autowired
    private RechargeService rechargeService;
    @Autowired
    private WeixinPayService weixinPayService;
    @Autowired
    private MQProducer mqProducer;
    @Autowired
    private TransationLogDao transationLogDao;
    @Autowired
    private RedisService redisService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private AdaPayService adaPayService;
    @Autowired
    private ReturnDepositService returnDepositService;
    @Autowired
    private RefundOrderDao refundOrderDao;
    @Autowired
    private ZfbPayConfigService zfbPayConfigService;
    @Autowired
    private UserService userService;
    @Autowired
    private AccountDao accountDao;
    @Autowired
    private RechargeMerchantService rechargeMerchantService;
    @Autowired
    private WeixinPayConfigService weixinPayConfigService;
    @Autowired
    private RechargeDao rechargeDao;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private UserAdaPayLogService userAdaPayLogService;
    @Autowired
    private PushMsgLogService pushMsgLogService;
    @Autowired
    private UserAccountLogService userAccountLogService;
    @Autowired
    private UserAccountMoneyService userAccountMoneyService;
    @Autowired
    private UserAccountMoneyDao userAccountMoneyDao;
    @Autowired
    private WeixinDepositLogService weixinDepositLogService;
    @Autowired
    private AdaPayLogDao adaPayLogDao;
    @Autowired
    private AccountService accountService;
    @Resource
    private RefundDoLogService refundDoLogService;



    public static void main(String[] args) {
        String timeStr = "2024-06-14 10:36:51";
        DateTime time = DateUtil.parse(timeStr);
        String time1 = time.toString();
        System.out.println(time1);
        Date time2 = DateUtil.parse(time1);
        System.out.println(time2);
    }

    @RabbitListener(queues = {"${mq.payqueue}"}, concurrency = "${mq.concurrency}", ackMode = "MANUAL")
    public void onMessage(Message message, Channel channel) throws IOException {
        Long startTime = System.currentTimeMillis();
        String respMsg = null;
        try {
            respMsg = new String(message.getBody(), "UTF-8");
            log.info("收到支付回调" + respMsg);
            /**判断消息类型*/
            PayData payData = JSON.parseObject(respMsg, PayData.class);
            handel(payData);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("消息消费异常", e);
            //异常消息直接推到
            mqProducer.sendToRide(RabbitMQData.dealqueue, RabbitMQData.dealqueue, respMsg);
            //channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
        log.info("支付处理完成，耗时【" + (System.currentTimeMillis() - startTime) + "】+ms");
    }

    /**
     * 主动查询订单支付详情
     *
     * @param message
     * @param channel
     * @throws IOException
     */
//    @RabbitListener(queues = {"${mq.orderqueue}"}, concurrency = "${mq.concurrency}", ackMode = "MANUAL")
    public void handelPay(Message message, Channel channel) throws IOException {

        Long startTime = System.currentTimeMillis();
        String respMsg = null;
        try {
            respMsg = new String(message.getBody(), "UTF-8");
            String json = JSON.parse(new String(message.getBody())).toString();
            log.info("收到主动查询信息" + json);

            PayCallbackData payCallbackData = JSON.parseObject(json, PayCallbackData.class);
            if (payCallbackData == null) {
                return;
            }
            CallbackDataVo callbackDataVo = payCallbackData.getData();
            if (callbackDataVo.getType() == 1) {
                //判断消息类型
                PayData payData = new PayData();
                payData.setDateTime(callbackDataVo.getConfirmTime());
                payData.setOut_trade_no(callbackDataVo.getOrderNo());
                payData.setTransaction_id(callbackDataVo.getTransactionId());
                payData.setPamentId(callbackDataVo.getPaymentId());
                payData.setFee(callbackDataVo.getFee_amt());
                handel(payData);
            } else {
                //退款
                if ("SUCCESS".equalsIgnoreCase(callbackDataVo.getStatus())) {
                    TransationLog transationLog = new TransationLog();
                    transationLog.setBusinessNO(callbackDataVo.getOrderNo());
                    transationLog.setTransactionState(TransationLogConstant.TRANSACTION_STATE_SUCCESS);
                    transationLog.setPayTime(DateUtil.parse(callbackDataVo.getConfirmTime()));
                    transationLog.setFinishTime(new Date());
                    transationLogDao.edit(transationLog);
                } else {
                    TransationLog transationLog = new TransationLog();
                    transationLog.setBusinessNO(callbackDataVo.getOrderNo());
                    transationLog.setTransactionState(TransationLogConstant.TRANSACTION_STATE_FAILURE);
                    transationLogDao.edit(transationLog);
                }
            }
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("消息消费异常", e);
            //异常消息直接推到
            mqProducer.sendToRide(RabbitMQData.dealqueue, RabbitMQData.dealqueue, respMsg);
            //channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
        log.info("主动查询支付处理完成，耗时【" + (System.currentTimeMillis() - startTime) + "】+ms");
    }

    /**
     * 主动查询订单支付详情
     *
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = {"${mq.orderqueue}"}, concurrency = "${mq.concurrency}", ackMode = "MANUAL")
    public void handelPayNew(Message message, Channel channel) throws IOException {
        log.info("进入消费者逻辑");
        Long startTime = System.currentTimeMillis();
        String respMsg = null;
        Integer userId = null;
        try {
            respMsg = new String(message.getBody(), "UTF-8");
            String json = JSON.parse(new String(message.getBody())).toString();
            log.info("收到主动查询信息" + json);

            PayCallbackData payCallbackData = JSON.parseObject(json, PayCallbackData.class);
            if (payCallbackData == null) {
                return;
            }
            CallbackDataVo callbackDataVo = payCallbackData.getData();
            if (callbackDataVo.getType() == 1) {    // 1 为支付
                /**判断消息类型*/
                PayData payData = new PayData();
                payData.setDateTime(callbackDataVo.getConfirmTime());
                payData.setOut_trade_no(callbackDataVo.getOrderNo());
                payData.setTransaction_id(callbackDataVo.getTransactionId());
                payData.setPamentId(callbackDataVo.getPaymentId());
                String fee_amt = callbackDataVo.getFee_amt();
                payData.setFee(fee_amt == null ? "0" : fee_amt);
                handel(payData);
            } else {    // 2 为退款
                // 退款情况下 OrderNo 存 退款订单号
                String refundNO = callbackDataVo.getOrderNo();
                if (!redisService.setNx(RedisConstant.REFUND_LOCK + "consumer" + refundNO, RedisConstant.REFUND_LOCK, 60)) {
                    log.warn("获取分布式锁失败{}", refundNO);
                    return;
                }
                try {
                    log.info("进入MQ消费者，开始消费退款消息");
                    // 对于金额变动要做幂等消费（ 可能存在重复消息 ）
                    //退款
                    RefundOrder refundOrder = refundOrderDao.getByRefundNO(refundNO);
                    if (Objects.isNull(refundOrder)){
                        log.error("refundorder为空，请排查refundorder插入问题,refundNO={}",refundNO);
                        return ;
                    }
                    // 判断消息是否被消费过,已消费消息跳过
                    if (refundOrder.getMsgSuccess()){
                        return ;
                    }
                    log.info("refundOrder信息={}", JSON.toJSONString(refundOrder));
                    if ("SUCCESS".equalsIgnoreCase(callbackDataVo.getStatus())) {
                        if ("复用字段-执行退押金逻辑分支".equals(refundOrder.getRemark())){
                            log.info("退押金逻辑");
                            // 判断是否退押金消息
                            Double refundMoney = refundOrder.getRefundMoney();
                            DateTime time = DateUtil.parse(callbackDataVo.getConfirmTime());
                            AdaPayLog adaPayLog = adaPayLogDao.getByAdaPayId(refundOrder.getRechargeNO());
                            log.info("退押金获取adapayLog为{}",JSON.toJSONString(adaPayLog));
                            User user = userDao.getByUserId(adaPayLog.getUserId());
                            log.info("退押金获取user为{}",JSON.toJSONString(user));
                            Integer accountId = adaPayLog.getAccountId();
                            dealRefundDeposit(refundMoney,refundNO,time,user,refundOrder,accountId);
                            return ;
                        }
                    }
                    // 业务订单号
                    String refundBusinessNO = refundOrder.getBusinessNO();
                    // 本次退款金额
                    Double refundMoney = refundOrder.getRefundMoney();

                    // 退款情况下 paymentId 存 充值订单号
                    String rechargeNO = refundOrder.getRechargeNO();

                    Recharge recharge = rechargeDao.getByOrderNO(rechargeNO);
                    log.info("单号={}，充值订单={}", rechargeNO, JSON.toJSONString(recharge));
                    userId = recharge.getUserId();
                    User user = userDao.getByUserId(userId);
                    Integer accountId = recharge.getAdAccountId();
                    Account account = accountDao.getByAccountId(accountId);
                    Integer operatorId = refundOrder.getOperatorId();
                    String operatorName = refundOrder.getOperatorName();
                    String operatorPhone = refundOrder.getOperatorPhone();
                    // 获取骑行订单号
                    String rideOrderNo = refundOrder.getRideOrderNO();
                    String transactionLogRemark = refundOrder.getRemark();
                    // 统一时间
                    DateTime time = DateUtil.parse(callbackDataVo.getConfirmTime());

                    AdaPayConfig adaPayConfig = null;
                    WeixinPayConfig weixinPayConfig = null;
                    ZfbPayConfig zfbPayConfig = null;
                    if (recharge.getType().equals(RechargeConstant.RECHARGE_WEIXIN_APP) || recharge.getType()
                            .equals(RechargeConstant.RECHARGE_WEIXIN_XCX)) {
                        // 查询用户使用的小程序appid
                        WeixinPayConfig brandWeixinPayConfig = weixinPayConfigService.getByAccountId(user.getAccountId(), recharge.getType());
                        String appId = brandWeixinPayConfig.getAppId();
                        /**1.根据订单号查询区域充值表获取支付配置*/
                        RechargeMerchant rechargeMerchant = rechargeMerchantService.getByOrderNO(recharge.getOrderNO());
                        if (null != rechargeMerchant) {
                            weixinPayConfig = weixinPayConfigService.getByPartnerAndAppId(rechargeMerchant.getPartner(),appId,false);//商户id，区域id，品牌id
                        }
                        if (weixinPayConfig == null) {
                            /**2.根据订单号没获取到区域充值表配置的，默认获取平台微信支付配置*/
                            weixinPayConfig = weixinPayConfigService.getByAccountId(user.getAccountId(), recharge.getType());
                        }
                    }else if (recharge.getType().equals(RechargeConstant.RECHARGE_ZFB_APP)) {
                        /**获取平台支付宝支付信息*/ /**支付宝app*/
                        zfbPayConfig = zfbPayConfigService.getByAccountId(user.getAccountId(), RechargeConstant.ZFB_PAY_APP);
                    }else if (recharge.getType().equals(RechargeConstant.RECHARGE_ZFB_XCX)) {
                        /**获取平台支付宝支付信息*/ /**支付宝小程序*/
                        zfbPayConfig = zfbPayConfigService.getByAccountId(user.getAccountId(), RechargeConstant.ZFB_PAY_XCX);
                    }else if (recharge.getType().equals(RechargeConstant.RECHARGE_PAY_ADAPAY) || recharge.getType().equals(RechargeConstant.RECHARGE_PAY_ADAPAY_ZFB)) {
                        /**汇通天下聚合支付*/
                        adaPayConfig = cacheService.getAdaPayConfig(user.getAccountId(),
                                AdaPayConstant.PAY_CHANNEL_WXXCX);
                    }

                    if ("SUCCESS".equalsIgnoreCase(callbackDataVo.getStatus())) {
                        log.info("退款消费消息getReturnResult，参数 account = {}，recharge = {}，refundNO = {}，" +
                                        "refundMoney = {}，user = {}，refundBusinessNO = {}，operatorId = {}，operatorName = {}，" +
                                        "operatorPhone = {}，rideOrderNo = {}，transactionLogRemark = {}",
                                JSON.toJSONString(account), JSON.toJSONString(recharge), refundNO, refundMoney, JSON.toJSONString(user), refundBusinessNO,
                                operatorId, operatorName, operatorPhone, rideOrderNo, transactionLogRemark);


                        String logTag = refundOrder.getLogTag();

                        refundDoLogService.dealLog(logTag,refundNO,time,zfbPayConfig,adaPayConfig,weixinPayConfig,message);

                        TransationLog transationLog = new TransationLog();
                        transationLog.setBusinessNO(callbackDataVo.getOrderNo());
                        transationLog.setTransactionState(TransationLogConstant.TRANSACTION_STATE_SUCCESS);
                        transationLog.setPayTime(time);
                        transationLog.setFinishTime(time);
                        log.info("操作交易记录表{}", JSON.toJSONString(transationLog));
                        transationLogDao.edit(transationLog);

                        // 更新refundOrder消息消费状态
                        refundOrder.setMsgSuccess(true);
                        refundOrderDao.updateMsgInfo(refundOrder);
                    } else {
                        TransationLog transationLog = new TransationLog();
                        transationLog.setBusinessNO(callbackDataVo.getOrderNo());
                        transationLog.setTransactionState(TransationLogConstant.TRANSACTION_STATE_FAILURE);
                        transationLogDao.edit(transationLog);
                        // 更新退款订单表状态为退款失败
                        refundOrder.setRefundStatus(RefundConstant.REFUND_FAIL);
                        refundOrderDao.updateMsgInfo(refundOrder);
                        log.info("退款失败,订单号=" + recharge.getOrderNO() + ",退款金额=" + refundMoney);
                    }
                }finally {
                    redisService.del(RedisConstant.REFUND_LOCK + refundNO);
                    redisService.del(RedisConstant.REFUND_LOCK + userId);
                    userService.unlockUserRefund(userId);
                }
            }
            log.info("即将对消费数据={}进行ack",JSON.toJSONString(payCallbackData));
        } catch (Exception e) {
            log.error("消息消费异常", e);
            //异常消息直接推到
            mqProducer.sendToRide(RabbitMQData.dealqueue, RabbitMQData.dealqueue, respMsg);
            //channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
        }finally {
            // 手动ACK
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
        log.info("主动查询支付处理完成，耗时【" + (System.currentTimeMillis() - startTime) + "】+ms");
    }

    /**
     * 延时分账处理
     *
     * @param message
     * @param channel
     * @throws IOException
     */
    @RabbitListener(queues = {"${mq.cashqueue}"}, concurrency = "${mq.concurrency}", ackMode = "MANUAL")
    public void handleCash(Message message, Channel channel) throws IOException {
        Long startTime = System.currentTimeMillis();
        String respMsg = null;
        try {
            respMsg = new String(message.getBody(), "UTF-8");
            log.info("收到延时分账请求" + respMsg);
            /**判断消息类型*/
            UserDelayPay userDelayPay = JSON.parseObject(respMsg, UserDelayPay.class);

            User user = userDao.getByUserId(userDelayPay.getUserId());
            /**执行分账*/
            log.info("消息队列记录区域,userId={},accountId={},orderNO={}",user.getUserId(),userDelayPay.getAdAccountId(),userDelayPay.getOrderNO());
            adaPayService.delay(userDelayPay.getMoney(), user, userDelayPay.getAdAccountId(), userDelayPay.getOrderNO(), userDelayPay.getRideMoney());

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("消息消费异常", e);
            //异常消息直接推到
            mqProducer.sendToRide(RabbitMQData.dealqueue, RabbitMQData.dealqueue, respMsg);
            //channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
        log.info("延时分账处理完成，耗时【" + (System.currentTimeMillis() - startTime) + "】+ms");
    }

    /**
     * 自动退押金逻辑
     *
     * @param message 推送消息体
     * @param channel 通道
     * @throws IOException
     */
    @RabbitListener(queues = {"${mq.returndepositqueue}"}, concurrency = "${mq.concurrency}", ackMode = "MANUAL")
    public void handleDeposit(Message message, Channel channel) throws IOException {
        Long startTime = System.currentTimeMillis();
        String respMsg = null;
        try {
            respMsg = new String(message.getBody(), "UTF-8");
            log.info("收到押金退还请求" + respMsg);
            /**判断消息类型*/
            DepositData depositData = JSON.parseObject(respMsg, DepositData.class);
            /**押金退还*/
            returnDepositService.apply(depositData.getAccountId(), depositData.getUserId(), null, null, null);

            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("消息消费异常", e);
            //异常消息直接推到
            mqProducer.sendToRide(RabbitMQData.dealqueue, RabbitMQData.dealqueue, respMsg);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
        log.info("押金退还处理完成，耗时【" + (System.currentTimeMillis() - startTime) + "】+ms");
    }

    /**
     * 处理支付回调
     *
     * @param payData
     */
    public void handel(PayData payData) {
        if (!redisService.setNx(RedisConstant.ORDER_NX + payData.getOut_trade_no(), "1", 5)) {
            log.warn("回调获取分布式锁失败" + payData.getOut_trade_no());
            return;
        }
        try {
            Recharge recharge = rechargeService.getByOrderNO(payData.getOut_trade_no());
            /**执行结束订单操作*/
            if (recharge != null && RechargeConstant.recharge_notcheck.equals(recharge.getState())) {
                if (recharge.getType().equals(RechargeConstant.RECHARGE_PAY_ADAPAY) || recharge.getType().equals(RechargeConstant.RECHARGE_PAY_ADAPAY_ZFB)) {
                    weixinPayService.pay(recharge, payData.getPamentId(), payData.getTransaction_id(), payData.getDateTime(), payData.getFee());
                } else {
                    weixinPayService.pay(recharge, payData.getOut_trade_no(), payData.getTransaction_id(), payData.getDateTime(), null);
                }
            } else {
                log.warn("查不到对应订单号" + payData.getOut_trade_no());
            }
        } finally {
            redisService.del(RedisConstant.ORDER_NX + payData.getOut_trade_no());
        }
    }


    private void dealRefundDeposit(Double refundMoney, String refundNO, Date time, User user, RefundOrder refundOrder, Integer accountId){
        log.info("执行dealRefundDeposit方法，参数为refundMoney={},refundNO={},time={},refundOrder={},accountId={}",refundMoney,refundNO,time,JSON.toJSONString(refundOrder),accountId);
        // 执行退押金记录
        WeixinDepositLog weixinDepositLog = weixinDepositLogService.getByOrderNo(refundOrder.getRechargeNO());


        List<UserAdaPayLog> userAdaPayLogs = userAdaPayLogService.getByPaymentId(refundOrder.getBusinessNO());
        // 存在useradapaylogs 时执行的记录
        if (!userAdaPayLogs.isEmpty()) {
            List<DivMembers> list = new ArrayList<>();
            for (UserAdaPayLog userAdaPayLog : userAdaPayLogs) {
                DivMembers divMembers = new DivMembers(userAdaPayLog.getUserNO(), String.format("%.2f", userAdaPayLog.getMoney().doubleValue()
                        / 100), "N");
                list.add(divMembers);
            }
            /**更改押金充值记录为已退款*/
            for (UserAdaPayLog userAdaPayLog : userAdaPayLogs) {
                userAdaPayLog.setRefundMoney(userAdaPayLog.getMoney());
                userAdaPayLog.setRefundServiceFee(userAdaPayLog.getServiceFee());
                userAdaPayLog.setRefundFee(userAdaPayLog.getFee());
                userAdaPayLog.setAllRefundMoney(userAdaPayLog.getMoney());
                userAdaPayLog.setRefundTime(time);
                userAdaPayLogService.editRefund(userAdaPayLog);
            }
            AdaPayLog adaPayLog = new AdaPayLog();
            adaPayLog.setRefundMoney(refundMoney);
            adaPayLog.setState(AdaPayConstant.ADAPAY_LOG_REFUND);
            adaPayLog.setAdaPayId(weixinDepositLog.getOut_trade_no());
            adaPayLog.setRefundNO(refundNO);
            adaPayLog.setRefundTime(time);
            adaPayLogDao.editRefund(adaPayLog);
            adaPayService.addAdaPayRefundLog(userAdaPayLogs, list, "refundNO", 0, 0,
                    0);
        }


        log.info("押金退还成功，支付平台订单号=" + weixinDepositLog.getTransaction_id());
        /**修改押金金额*/
        userService.updateDepositMoney(user.getUserId(), -weixinDepositLog.getDepositMoney());
//        returnSuccNum++;
        /**更新押金退还记录*/
        WeixinDepositLog weixinDepositLogUpdate = new WeixinDepositLog();
        weixinDepositLogUpdate.setReturnTime(time.toString());
        weixinDepositLogUpdate.setTransaction_id(weixinDepositLog.getTransaction_id());
        weixinDepositLogUpdate.setOut_refund_no(refundNO);
        weixinDepositLogService.updateReturn(weixinDepositLogUpdate);
        /**记录资金变动日志*/
        UserAccountLog userAccountLog = new UserAccountLog();
        userAccountLog.setMoneyType(0);
        userAccountLog.setAccountId(accountId);
        userAccountLog.setMoney(weixinDepositLog.getDepositMoney());
        userAccountLog.setUserId(user.getUserId());
        userAccountLog.setOperaTime(time.toString());
        userAccountLog.setRemark("押金退还");
        userAccountLog.setType(0);
        userAccountLogService.insert(userAccountLog);
        String orderNo = weixinDepositLog.getOut_trade_no();
        if (weixinDepositLog.getType().equals(RechargeConstant.RECHARGE_PAY_ADAPAY)
                || weixinDepositLog.getType().equals(RechargeConstant.RECHARGE_PAY_ADAPAY_ZFB)) {
            AdaPayLog adaPayLog = adaPayLogDao.getByAdaPayId(weixinDepositLog.getOut_trade_no());
            orderNo = adaPayLog.getOrderNO();
        }
        Recharge recharge = rechargeService.getByOrderNO(orderNo);
        log.info("查询区域押金：userId=" + user.getUserId() + "accountId=" + recharge.getAdAccountId());
        UserAccountMoney depositMoney = userAccountMoneyService.getByAccountId(user.getUserId(), BalanceLogChangeTypeContent.capitalType_deposit, recharge.getAdAccountId());
        if (depositMoney != null) {
            depositMoney.setMoney(-depositMoney.getMoney());
            depositMoney.setUpdateTime(time.getTime());
            userAccountMoneyDao.edit(depositMoney);
        }
        List<String> merchantNOList = new ArrayList<>();
        merchantNOList.add(recharge.getOrderNO());
        Account account = accountService.getByAccountId(recharge.getAdAccountId());
        adaPayService.pushRefundDetailLog(user, account, weixinDepositLog.getDepositMoney(), refundNO, refundNO,
                recharge, refundOrder.getOperatorId(), refundOrder.getOperatorName(), refundOrder.getOperatorPhone(), BusinessConstant.BUSINESS_USER_REFUND_DEPOSIT, null, null,time);
        adaPayService.pushRefundLog(user, account, weixinDepositLog.getDepositMoney(), refundNO, merchantNOList, recharge, RefundLogContent.deposit_Refund,
                null, refundOrder.getOperatorId(), refundOrder.getOperatorName(), refundOrder.getOperatorPhone(), null,new DateTime(time));
        BalanceChange balanceChange = new BalanceChange(user.getUserId(), user.getPhone(), user.getName()
                , account.getAccountId(), user.getAccountId(), weixinDepositLog.getDepositMoney().longValue(), weixinDepositLog.getDepositMoney().longValue()
                , 0L, IncomeTypeContent.inComeRefund,
                BalanceLogChangeTypeContent.capitalType_deposit, BalanceLogCapitalTypeContent.USER_REFUNDS_DEPOSIT
                , time.getTime(), "退押金", refundNO);
        pushMsgLogService.sendPushLog(JSON.toJSONString(balanceChange), TableNameConstant.BALANCECHANGE);
    }
}
